package com.jin.jpa.wrapper.expression;

import com.jin.jpa.wrapper.LambdaWrapperContext;

import javax.persistence.criteria.*;

/**
 * @Author: yuanxiuyao
 * @Date: 2024/1/8 16:31
 * @PackageName: org.example.jpa.wrapper.expression
 * @Version 1.0
 */
public class ScopeExpression implements IExpression<Predicate>{

    private String field;

    private ScopeOp scopeOp;

    private Object value1;

    private Object value2;

    private ScopeExpression(String field, ScopeOp scopeOp, Object value1, Object value2){
        this.field = field;
        this.scopeOp = scopeOp;
        this.value1 = value1;
        this.value2 = value2;
    }

    public static ScopeExpression of(String field, ScopeOp scopeOp, Object value1, Object value2){
        return new ScopeExpression(field, scopeOp, value1, value2);
    }

    @Override
    public Predicate toHandle(LambdaWrapperContext<?> context) {
        Root<?> root = context.getRoot();
        CriteriaBuilder criteriaBuilder = context.getCriteriaBuilder();
        Path<Comparable> expression = root.get(field);
        switch (scopeOp) {
            case BETWEEN:
                return criteriaBuilder.between(expression, (Comparable)value1, (Comparable)value2);
            case NOT_BETWEEN:
                return criteriaBuilder.between(expression, (Comparable)value1, (Comparable)value2).not();
        }
        return null;
    }

    public enum ScopeOp{
        BETWEEN,
        NOT_BETWEEN
    }
}
